package tool.zyk.stardand;

import lombok.Data;
import lombok.ToString;
import tool.zyk.consts.RpcCommonConst;
import tool.zyk.consts.RpcOrderTypeEnum;
import tool.zyk.consts.SerializableTypeEnum;
import tool.zyk.dto.RpcOrderTypeDTO;
import tool.zyk.dto.SerializableDTO;
import tool.zyk.generator.RequestIdGenerator;
import tool.zyk.utils.Asserts;

import java.util.Objects;

/**
 * author: zyk
 * datetime: 2024/1/27 16:04
 * describe: 自定义PRC协议
 */
@Data
@ToString
public class RpcProtocol {
    //请求ID
    private Long requestId;
    //魔法值
    private byte[] magicNum;
    //序列化类型
    private SerializableDTO serializableType;
    //指令类型
    private RpcOrderTypeDTO orderType;
    //数据长度
    private Integer dataLength;
    //数据
    private byte[] data;


    private static RpcProtocol ofProtocol(byte[] data, SerializableTypeEnum serializableTypeEnum) {
        Asserts.isNotNull(serializableTypeEnum, "序列化类型不能为空");
        Asserts.isNotNull(data, "传输数据不能");
        RpcProtocol rpcProtocol = new RpcProtocol();
        rpcProtocol.setRequestId(RequestIdGenerator.generateRequestId());
        rpcProtocol.setMagicNum(RpcCommonConst.MAGIC_NUM);
        rpcProtocol.setSerializableType(serializableTypeEnum.ofDTO());
        rpcProtocol.setDataLength(Objects.isNull(data) ? 0 : data.length);
        rpcProtocol.setData(data);
        return rpcProtocol;
    }


    public static RpcProtocol ofRequest(byte[] data, SerializableTypeEnum serializableTypeEnum) {
        Asserts.isNotNull(data, "要传输的信息为null");
        RpcProtocol rpcProtocol = ofProtocol(data, serializableTypeEnum);
        rpcProtocol.setOrderType(RpcOrderTypeEnum.REQUEST.ofDto());
        return rpcProtocol;
    }

    public static RpcProtocol ofResponse(byte[] data, SerializableTypeEnum serializableTypeEnum) {
        Asserts.isNotNull(data, "要传输的信息为null");
        RpcProtocol rpcProtocol = ofProtocol(data, serializableTypeEnum);
        rpcProtocol.setOrderType(RpcOrderTypeEnum.RESPONSE.ofDto());
        return rpcProtocol;
    }


}
